<?php

namespace app\admin\controller;

use app\common\model\UserApplyModel;
use app\common\model\UserModel;
use app\service\UserService;
use think\facade\Request;
use think\Db;

class UserApplyController extends BaseController
{
    const PASS = 1; //通过状态

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        return view("index");
    }

    public function dataGrids()
    {
        $all_request = $this->getAllParams();
        $where       = [];
        $model       = UserApplyModel::field('*');

        if (is_numeric($user_id = $this->get('user_id'))) {
            $model = $model->where('user_id', $user_id);
        }

        if (in_array($status = $this->get('status', ''), ['0', '1', '2', '3'])) {
            $model = $model->where('status', $status);
        }

        if (in_array($change_source = $this->get('change_source', ''), ['0', '1', '2'])) {
            $model = $model->where('change_source', $change_source);
        }

        if (in_array($change_type = $this->get('change_type', ''), ['0', '3'])) {
            $model = $model->where('change_type', $change_type);
        } else {
            $model = $model->whereIn('change_type', [0, 3]);
        }

        if (strtotime($start_time = $this->get('start_time', '')) && strtotime($end_time = $this->get('end_time', ''))) {
            $model = $model->whereBetween('updated_at', [$start_time, $end_time]);
        } elseif (strtotime($start_time)) {
            $model = $model->whereBetween('updated_at', [$start_time, date('Y-m-d H:i:S')]);
        }

        if ($original_data = trim($this->get('original_data', ''))) {
            $model = $model->whereLike('original_data', $original_data . '%');
        }

        return json([
            "count" => $model->count('id'),
            "data"  => $model->order("id", "desc")
                ->page($this->get('page', 1), $this->get('limit'))
                ->select()
                ->toArray(),
            "code"  => 0,
            "msg"   => "",
        ]);
    }

    /**
     * 审核用户修改数据
     * @return \think\response\Json
     */
    public function operation()
    {
        $id     = Request::post("id", 0);
        $status = Request::post("status", 0);

        $find = UserApplyModel::where("id", $id)->find();
        if (!$find) {
            return self::bulidFail("未查询到相关数据");
        }

        if ($find["status"] != 0 || $find["status"] == $status) {
            return self::bulidSuccess(null, "您已操作该数据");
        }

        $userFind = UserModel::where("id", $find["user_id"])->find();
        if (!$userFind) {
            return self::bulidFail("该用户不存在");
        }

        // 日志
        $log_content = '';

        Db::startTrans();
        if ($status == self::PASS) {
            switch ($find->change_type) {
                case 0:
                    $userFind->nick_name = $find["new_data"];
                    $ret                 = $userFind->save();
                    if ($ret === false) {
                        Db::rollback();
                        return self::bulidFail("更新昵称失败");
                    }
                    break;
                case 1:
                    $userFind->mobile = $find["new_data"];
                    $ret              = $userFind->save();
                    if ($ret === false) {
                        Db::rollback();
                        return self::bulidFail("更新手机号失败");
                    }
                    break;
                case 2:
                    $userFind->avatar = $find["new_data"];
                    $ret              = $userFind->save();
                    if ($ret === false) {
                        Db::rollback();
                        return self::bulidFail("更新头像失败");
                    }
                    break;
                case 3:
                    // 账号类型修改
                    $old_account_type = UserModel::userAccountType($userFind->is_anchor, $userFind->anchor_type);
                    $account_type     = intval($find["new_data"]);

                    // 主播账号类型数组  如果原始数据用户不是主播，修改成主播的
                    $anchor_account_typearr = [3, 4, 5];
                    if (!in_array($old_account_type, $anchor_account_typearr) && in_array($account_type, $anchor_account_typearr)) {
                        // 秘钥为空则生成一个
                        // $userFind->anchor_secret = empty($userFind->anchor_secret) ? md5(uniqid() . time()) : $userFind->anchor_secret;
                        $userFind->auth_time = strtotime($userFind->auth_time) <= 0 ? date("Y-m-d H:i:s") : $userFind->auth_time;
                    }

                    // 更改账号类型字段
                    switch ($account_type) {
                        case 1;
                            $userFind->is_anchor   = 0;
                            $userFind->anchor_type = 1;
                            break;
                        case 2;
                            $userFind->is_anchor   = 0;
                            $userFind->anchor_type = 3;
                            break;
                        case 3;
                            $userFind->is_anchor   = 1;
                            $userFind->anchor_type = 1;
                            break;
                        case 4;
                            $userFind->is_anchor   = 1;
                            $userFind->anchor_type = 2;
                            break;
                        case 5;
                            $userFind->is_anchor   = 1;
                            $userFind->anchor_type = 3;
                            break;
                    }

                    $ret = $userFind->save();
                    if ($ret === false) {
                        Db::rollback();
                        return self::bulidFail("更新账号类型失败");
                    }
                    break;
                default:
                    Db::rollback();
                    return self::bulidFail("错误的修改类型");
            }

            // 记录日志
            $log_content = $this->admin_name . "操作通过用户({$userFind->id})，ID:{$id}的信息审核";
        } else {

            if ($find->change_type == 0) {
                $userFind->nick_name = $find->original_data;
                if (!$userFind->save()) {
                    return static::bulidFail("驳回失败");
                }
            }
            // 记录日志
            $log_content = "操作驳回用户({$userFind->id})，ID:{$id}的信息审核";
        }

        $resp = UserApplyModel::where("id", $id)->update([
            "status" => $status
        ]);

        if ($resp === false) {
            Db::rollback();
            return self::bulidFail("操作失败");
        }

        if ($userFind->is_anchor == 1) {
            // 设置es 主播数据
            $res = UserService::setAnchorEs($userFind->id);
            if ($res['code'] != 0) {
                throw new \Exception('修改信息失败');
            }
        } else {
            // 不是主播则删除es数据
            UserService::delAnchorEs($userFind->id);
        }

        // 记录日志
        parent::addAdminLog($log_content, $userFind->id);

        Db::commit();

        // 清理主播缓存,修改过账号类型的清理缓存
        if ($find->change_type == 3) {
            UserModel::delAnchorCache();
        }

        return self::bulidSuccess();
    }
}
